LINQ to XML - Sorting Operator Samples


LINQ, LINQ to XML, .NET Framework 4.0
LINQ, LINQ to XML, XML, Console Window, XML Documentation
Desktop, Data
en-US
6/28/2011

Introduction

These samples demonstrate how to sort results using "orderby" in LINQ to XML.

Building the Sample

  1. Open Program.cs
  2. Uncomment the line for the sample that you want to run; comment ones you don't want to run
  3. Press Ctrl + F5

Screenshot

Sample Code

C#
Edit|Remove
            [Category("Sort")] 
            [Description("Sort customers by name in ascending order")] 
            public void XLinq56() 
            { 
                XDocument doc = XDocument.Load("nw_customers.xml"); 
                var query = 
                    from 
                        customer in doc.Descendants("Customers") 
                    orderby 
                        (string)customer.Elements("ContactName").First() 
                    select 
                        customer.Element("ContactName"); 
                XElement result = 
                    new XElement("SortedCustomers", query); 
                Console.WriteLine(result); 
            }

Source Code Files

More Information

For more information on LINQ to XML: http://msdn.microsoft.com/en-us/library/bb387098.aspx